//
//  ServiceConnector.m
//  POS
//
//  Created by sigma xu on 5/6/13.
//  Copyright (c) 2013 sigma xu. All rights reserved.
//

#import "ServiceConnector.h"

@interface ServiceConnector ()
{
    NSData *receivedData;
//    NSMutableData *receivedData1;
    NSString *new_so_number;
    NSMutableArray *favorite_client_list;
}


@end

@implementation ServiceConnector;

//@synthesize receivedData1;

-(void)test_connection{
    
//    receivedData = [[NSMutableData alloc] init];
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString * url;
    url = [prefs stringForKey:@"server_url"];
    //build up the request that is to be sent to the server
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    NSString *contenttype=@"multipart/form-data";
    [request addValue:@"Content-Type" forHTTPHeaderField:contenttype];
    [request addValue:@"test_connection" forHTTPHeaderField:@"METHOD"];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if(!connection){
        NSLog(@"Connection Failed");
    }
}
-(void)syncDB{
    ClientDBO *cdbo = [[ClientDBO alloc] init];
    favorite_client_list=cdbo.load_favorites_list;
    [cdbo clear_client];
    [self request_client:@"1"];
//    receivedData1 = [[NSMutableData alloc] init];
//    [self request_all_client];
    [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
}
-(void)request_item:(NSString *)row{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString * url;
    if ([[prefs stringForKey:@"server_url"] isEqualToString:@""]) {
        url = @"http://localhost/posws/app/";
    }else{
        url = [prefs stringForKey:@"server_url"];
    }
    //build up the request that is to be sent to the server
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    NSString *contenttype=@"multipart/form-data";
    [request addValue:@"Content-Type" forHTTPHeaderField:contenttype];
    [request addValue:@"request_item" forHTTPHeaderField:@"METHOD"];
    //create data that will be sent in the post
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:row forKey:@"row"];
    //serialize the dictionary data as json
    NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:nil];
    [request setHTTPBody:data]; //set the data as the post body
    [request addValue:[NSString stringWithFormat:@"%d",data.length] forHTTPHeaderField:@"Content-Length"];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if(!connection){
        NSLog(@"Connection Failed");
    }
}
-(void)request_all_client{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString * url;
    url = [prefs stringForKey:@"server_url"];
    //build up the request that is to be sent to the server
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    NSString *contenttype=@"multipart/form-data";
    [request addValue:@"Content-Type" forHTTPHeaderField:contenttype];
    [request addValue:@"request_all_client" forHTTPHeaderField:@"METHOD"];
    //create data that will be sent in the post
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    //serialize the dictionary data as json
    NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:nil];
    [request setHTTPBody:data]; //set the data as the post body
    [request addValue:[NSString stringWithFormat:@"%d",data.length] forHTTPHeaderField:@"Content-Length"];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if(!connection){
        NSLog(@"Connection Failed");
    }
}
-(void)request_client:(NSString *)row{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString * url;
    url = [prefs stringForKey:@"server_url"];
    //build up the request that is to be sent to the server
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    NSString *contenttype=@"multipart/form-data";
    [request addValue:@"Content-Type" forHTTPHeaderField:contenttype];
    [request addValue:@"request_client" forHTTPHeaderField:@"METHOD"];
    //create data that will be sent in the post
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:row forKey:@"row"];
    //serialize the dictionary data as json
    NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:nil];
    [request setHTTPBody:data]; //set the data as the post body
    [request addValue:[NSString stringWithFormat:@"%d",data.length] forHTTPHeaderField:@"Content-Length"];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if(!connection){
        NSLog(@"Connection Failed");
    }
}
-(void)post_sales_order_item_list:(NSString *)so_id{
    //post item list
    ItemDBO *idbo = [[ItemDBO alloc] init];
    NSMutableArray *item_list = [[NSMutableArray alloc] init];
    item_list = [idbo load_item_list_from_so:so_id];
    NSMutableArray *data = [[NSMutableArray alloc] init];
    for (int i = 0; i<[item_list count]; i++) {
        ItemDBO *idbo = [[ItemDBO alloc] init];
        idbo = [item_list objectAtIndex:i];
        NSDictionary *item_dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   new_so_number,@"so_number",
                                   idbo.item_barcode,@"item_barcode",
                                   idbo.item_name,@"item_name",
                                   idbo.item_package,@"item_package",
                                   idbo.quantity,@"quantity",
                                   idbo.unit,@"unit",
                                   idbo.unit_price,@"unit_price",
                                   nil];
        [data addObject:item_dict];
    }
    NSData *post = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString * url;
    if ([[prefs stringForKey:@"server_url"] isEqualToString:@""]) {
        url = @"http://localhost/posws/app/";
    }else{
        url = [prefs stringForKey:@"server_url"];
    }
    //build up the request that is to be sent to the server
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    NSString *contenttype=@"multipart/form-data";
    [request addValue:@"Content-Type" forHTTPHeaderField:contenttype];
    [request addValue:@"update_sales_order_item_list" forHTTPHeaderField:@"METHOD"];
    [request addValue:[NSString stringWithFormat:@"%d",post.length] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:post];
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [request setTimeoutInterval:5];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if(!connection){
        NSLog(@"Connection Failed");
    }
}
-(void)post_sales_order:(NSString *)so_id{
    //get so by id
    SalesOrderDBO *sodbo = [[SalesOrderDBO alloc] init];
    sodbo.so_id = so_id;
    sodbo = [sodbo get_sales_order_by_so_id];
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString * url;
    if ([[prefs stringForKey:@"server_url"] isEqualToString:@""]) {
        url = @"http://localhost/posws/app/";
    }else{
        url = [prefs stringForKey:@"server_url"];
    }
    //build up the request that is to be sent to the server
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    NSString *contenttype=@"multipart/form-data";
    [request addValue:@"Content-Type" forHTTPHeaderField:contenttype];
    [request addValue:@"post_sales_order" forHTTPHeaderField:@"METHOD"];
    
    //create data that will be sent in the post
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:sodbo.so_id forKey:@"so_id"];
    [dictionary setValue:sodbo.so_number forKey:@"so_number"];
    [dictionary setValue:sodbo.create_date forKey:@"create_date"];
    [dictionary setValue:sodbo.sales_man forKey:@"sales_man"];
    [dictionary setValue:sodbo.total_amount forKey:@"total_amount"];
    [dictionary setValue:sodbo.total_item forKey:@"total_item"];
    [dictionary setValue:sodbo.status forKey:@"status"];
    [dictionary setValue:sodbo.client forKey:@"client"];
    [dictionary setValue:sodbo.remark forKey:@"remark"];
    //serialize the dictionary data as json
    NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:nil];
    
    [request setHTTPBody:data]; //set the data as the post body
    [request addValue:[NSString stringWithFormat:@"%d",data.length] forHTTPHeaderField:@"Content-Length"];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if(!connection){
        NSLog(@"Connection Failed");
    }
}
#pragma mark - Data connection delegate -
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ // executed when the connection receives data
    NSLog(@"received data");
//    receivedData1 = [[NSMutableData alloc] init];
//    [receivedData1 appendData:data];
    receivedData = data;

}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ //executed when the connection fails
    
    NSLog(@"Connection failed with error: %@",error);
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                   message: [[NSString alloc] initWithFormat:@"%@",error]
                                                  delegate: self
                                         cancelButtonTitle:@"OK"
                                         otherButtonTitles:nil];
    [alert show];
}
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
    
    /*This message is sent when there is an authentication challenge ,our server does not have this requirement so we do not need to handle that here*/
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSError *error;
    int row = 0;
    int total_rows = 0;
//    NSLog(@"Request Complete,recieved %d bytes of data",receivedData.length);
    NSLog(@"data is %@",[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]);
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:&error];
    if(!json){
        NSLog(@"Error Json: %@",error);
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                       message: [[NSString alloc] initWithFormat:@"%@",error]
                                                      delegate: self
                                             cancelButtonTitle:@"OK"
                                             otherButtonTitles:nil];
        [alert show];
    }else if([[json objectForKey:@"status"] isEqualToString:@"success"]){
        if ([[json objectForKey:@"function"] isEqualToString:@"post_sales_order"]){
            SalesOrderDBO *sodbo = [[SalesOrderDBO alloc] init];
            sodbo.so_id = [json objectForKey:@"so_id"];
            sodbo = [sodbo get_sales_order_by_so_id];
            new_so_number = [json objectForKey:@"so_number"];
            sodbo.so_number = [json objectForKey:@"so_number"];
            sodbo.status = @"2";
            [sodbo update_sales_order];
            [self post_sales_order_item_list:sodbo.so_id];
        }
        if ([[json objectForKey:@"function"] isEqualToString:@"update_sales_order_item_list"]){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                           message: @"SQ has been posted"
                                                          delegate: self
                                                 cancelButtonTitle:@"OK"
                                                 otherButtonTitles:nil];
            alert.tag = 2;
            [alert show];
        }
        if ([[json objectForKey:@"function"] isEqualToString:@"test_connection"]){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                           message: @"Database connection success"
                                                          delegate: self
                                                 cancelButtonTitle:@"OK"
                                                 otherButtonTitles:nil];
            alert.tag = 3;
            [alert show];
        }
        if ([[json objectForKey:@"function"] isEqualToString:@"request_client"]){
            row = [[json objectForKey:@"row"] integerValue];
            total_rows = [[json objectForKey:@"total_rows"] integerValue];
            //insert new client
            ClientDBO *cdbo = [[ClientDBO alloc] init];
            cdbo.client_code=[json objectForKey:@"client_code"];
            cdbo.client_name=[json objectForKey:@"client_name"];
            cdbo.contact=[json objectForKey:@"contact"];
            cdbo.tel=[json objectForKey:@"tel"];
            cdbo.fax=[json objectForKey:@"fax"];
            cdbo.address=[json objectForKey:@"address"];
            cdbo.status=@"1";
            [cdbo insert_client];
            if (row<total_rows) {
                row = row +1;
                [self request_client:[NSString stringWithFormat:@"%d",row]];
            }else{
                
                //set up previous favorate
                for (ClientDBO *cdbo in favorite_client_list) {
                    [cdbo add_client_to_favorite:cdbo.id_client];
                }
                //start to sync item
                NSLog(@"Client Synced");
//                UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
//                                                               message: @"DB has synced"
//                                                              delegate: self
//                                                     cancelButtonTitle:@"OK"
//                                                     otherButtonTitles:nil];
//                alert.tag = 1;
//                [alert show];
//                [[UIApplication sharedApplication] setIdleTimerDisabled: NO];
                ItemDBO *idbo = [[ItemDBO alloc] init];
                [idbo clear_item];
                [self request_item:@"1"];
            }
        }
        if ([[json objectForKey:@"function"] isEqualToString:@"request_item"]){
            row = [[json objectForKey:@"row"] integerValue];
            total_rows = [[json objectForKey:@"total_rows"] integerValue];
            //insert new client
            ItemDBO *idbo = [[ItemDBO alloc] init];
            idbo.item_barcode=[json objectForKey:@"item_barcode"];
            idbo.item_brand=[json objectForKey:@"item_description"];
            idbo.item_name=[json objectForKey:@"item_name"];
            idbo.item_package=[json objectForKey:@"item_package"];
            idbo.unit=[json objectForKey:@"unit"];
            idbo.unit_price=[json objectForKey:@"unit_price"];
            [idbo insert_item];
            if (row<total_rows) {
                row = row +1;
                [self request_item:[NSString stringWithFormat:@"%d",row]];
            }else{
                //finish sync db
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                               message: @"DB has synced"
                                                              delegate: self
                                                     cancelButtonTitle:@"OK"
                                                     otherButtonTitles:nil];
                alert.tag = 1;
                [alert show];
                [[UIApplication sharedApplication] setIdleTimerDisabled: NO];
            }
        }
    }
    

//
//    [self requestReturnedData:receivedData];//send the data to the delegate
}
#pragma mark - ServiceConnectorDelegate -
-(void)requestReturnedData:(NSData *)data{ //activated when data is returned
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    NSLog(@"jason date is %@",dictionary);
}
@end
